<template>
  <div class="app-container">
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="120px"
      class="data-form"
      v-loading="loading"
    >
      <el-form-item label="基本信息">
        <el-collapse>
          <el-collapse-item>
            <template slot="title">
              <i class="el-icon-caret-right"></i>查看患者基本信息
            </template>
            <el-descriptions class="margin-top" :column="3" border>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-price-tag"></i>
                  患者编号
                </template>
                {{ patientInfo.id }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-user"></i>
                  患者姓名
                </template>
                {{ patientInfo.name }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-mobile-phone"></i>
                  患者手机号
                </template>
                {{ patientInfo.phone }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-timer"></i>
                  患者创建时间
                </template>
                {{ patientInfo.createTime }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-paperclip"></i>
                  是否绑定医生
                </template>
                <el-tag size="small">{{ patientInfo.hasDoctor ? "是" : "否" }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item>
                <template slot="label">
                  <i class="el-icon-tickets"></i>
                  患者备注
                </template>
                {{ patientInfo.remark ? patientInfo.remark : "暂无" }}
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>
      </el-form-item>

      <el-form-item label="患者姓名" prop="name">
        <el-input v-model="dataForm.name" placeholder="请输入患者姓名"></el-input>
      </el-form-item>

      <el-form-item label="患者来源" prop="subId">
        <el-cascader
          style="width: 230px"
          v-model="subIds"
          :props="defaultProps"
          @change="handleSubChange"
          clearable
          :options="deptOptions"
        ></el-cascader>
      </el-form-item>

      <el-form-item label="门诊号" prop="patientNumber">
        <el-input v-model="dataForm.patientNumber" placeholder="请输入门诊号"></el-input>
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="dataForm.sex">
              <el-radio
                border
                v-for="dict in dict.type.sys_user_sex"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input-number
              v-model="dataForm.age"
              :min="1"
              :max="150"
              label="描述文字"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="身份证号" prop="idNumber">
        <el-input v-model="dataForm.idNumber" placeholder="请输入身份证号"></el-input>
      </el-form-item>

      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input v-model="dataForm.phoneNumber" placeholder="请输入联系电话"></el-input>
      </el-form-item>

      <el-row>
        <el-col :span="8">
          <el-form-item label="民族" prop="nation">
            <el-select
              style="width: 230px"
              allow-create
              filterable
              v-model="dataForm.nation"
              placeholder="请选择民族"
            >
              <el-option
                v-for="(item, index) in dict.type.patient_info_nation"
                :key="index"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="婚姻" prop="marriage">
            <el-select
              style="width: 230px"
              v-model="dataForm.marriage"
              placeholder="请选择婚姻类型"
            >
              <el-option
                v-for="(item, index) in dict.type.patient_info_marriage"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职业" prop="profession">
            <el-select
              style="width: 230px"
              allow-create
              filterable
              v-model="dataForm.profession"
              placeholder="请选择职业"
            >
              <el-option
                v-for="(item, index) in dict.type.patient_info_profession"
                :key="index"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="身高" prop="height">
            <el-input
              style="width: 230px"
              @change="getBMI"
              v-model="dataForm.height"
              placeholder="请输入身高 [cm]"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="体重" prop="weight">
            <el-input
              style="width: 230px"
              @change="getBMI"
              v-model="dataForm.weight"
              placeholder="请输入体重 [kg]"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="体质指数(BMI)" prop="patientBmi">
            <el-input
              style="width: 230px"
              :disabled="true"
              v-model="dataForm.patientBmi"
              placeholder
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="运动频率" prop="exercise">
        <el-input
          v-model="dataForm.exercise"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          show-word-limit
          maxlength="300"
          placeholder="请输入患者常见运动，以及运动频率。如：一周跑步3次，每次2公里"
        ></el-input>
      </el-form-item>

      <el-form-item label="烟、酒摄入史" prop="ingestHistory">
        <el-input
          v-model="dataForm.ingestHistory"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          show-word-limit
          maxlength="300"
          placeholder="每周饮酒**次，每次**g（啤酒、红酒、洋酒可以统一换算成52°的白酒），共计饮酒多少年;每天吸烟多少支（叶子烟、雪茄、细支等可以换算成普通长支粗烟），共计吸烟多少年；特殊药物比如激素等摄入史"
        ></el-input>
      </el-form-item>
      <el-form-item label="发病节气" prop="patientTerm">
        <el-date-picker
          style="margin-right: 10px"
          v-model="termTimeList"
          type="daterange"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
        <el-tooltip
          class="item"
          effect="dark"
          content="生成查看时间段内所有节气"
          placement="top"
        >
          <el-button
            style="margin-right: 10px"
            size="medium"
            type="text"
            icon="el-icon-caret-right"
            @click="getSolarTerms"
            >获取节气</el-button
          >
        </el-tooltip>

        <el-select
          style="width: 330px"
          multiple
          v-model="patientTerm"
          placeholder="请选择发病节气"
          @change="getPatientTerm"
        >
          <el-option
            v-for="(item, index) in patientTermList"
            :key="index"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="病史是否可靠" prop="patientHistoryReliable">
        <el-radio-group v-model="dataForm.patientHistoryReliable">
          <el-radio border :label="1">可靠</el-radio>
          <el-radio border :label="0">不可靠</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="出生地" prop="birthAddress">
        <district @getAddress="getBirthAddress" ref="birthAddress"></district>
      </el-form-item>

      <el-form-item label="现居住地" prop="presentAddress">
        <district @getAddress="getPresentAddress" ref="presentAddress"></district>
      </el-form-item>

      <el-form-item label="紧急联系人电话" prop="emergencyContactNumber">
        <el-input
          v-model="dataForm.emergencyContactNumber"
          placeholder="请输入电话号码"
        ></el-input>
      </el-form-item>

      <el-form-item label="就诊时间" prop="clinicTime">
        <el-date-picker
          style="width: 230px"
          v-model="dataForm.clinicTime"
          type="datetime"
          placeholder="选择日期时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
    </el-form>

    <div style="text-align: center" v-if="isUpdate">
      <el-button type="primary" :loading="buttonLoading" @click="updateData"
        >修改基础入组信息</el-button
      >
    </div>
    <div style="text-align: center" v-else>
      <el-button type="primary" :loading="buttonLoading" @click="saveOrUpdateData"
        >保存并下一步</el-button
      >
    </div>
  </div>
</template>

<script>
import { isIdNumber } from "@/utils/validate";
import { isPhone } from "@/utils/validate";
import District from "../district";
import {
  getPatientInfo,
  saveBasicInfo,
  updateBasicInfo,
  queryBasicInfo,
  getSolarTerms,
} from "@/api/gonitis/basicInfo";
import { subTree } from "@/api/gonitis/illSub";
import arrayJSON from "@/assets/json/basicInfoArray.json";

export default {
  name: "BasicInfo",
  dicts: [
    "sys_user_sex",
    "patient_info_nation",
    "patient_info_marriage",
    "patient_info_profession",
  ],
  components: {
    District,
  },
  data() {
    //这里存放数据
    return {
      termTimeList: [],
      subIds: [],
      // 病情多选框映射
      defaultProps: {
        children: "children",
        label: "label",
        value: "id",
      },
      // 病情列表
      deptOptions: [],
      // form表单加载
      loading: false,
      buttonLoading: false,
      // 更新还是新增 true：更新 false： 新增
      isUpdate: false,
      patientInfo: {},
      patientTermList: [],
      patientTerm: [],
      dataForm: {
        id: null,
        subId: null,
        patientId: null,
        patientNumber: "",
        patientBmi: null,
        presentAddress: "",
        birthAddress: "",
        sex: null,
        age: null,
        idNumber: "",
        phoneNumber: "",
        nation: null,
        marriage: null,
        profession: null,
        height: null,
        weight: null,
        exercise: "",
        ingestHistory: "",
        patientTerm: "",
        patientHistoryReliable: null,
        clinicTime: null,
        emergencyContactNumber: "",
      },
      dataRule: {
        name: [
          {
            message: "患者姓名不能为空",
            required: true,
            trigger: ["blur"],
          },
        ],
        subId: [
          {
            message: "患者来源不能为空",
            required: true,
            trigger: ["change"],
          },
        ],
        patientNumber: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("门诊号必须填写"));
              } else if (!/^[0-9]+.?[0-9]*/.test(value)) {
                callback(new Error("身高必须为数字值"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: "blur",
          },
        ],
        idNumber: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("身份证号必须填写"));
              } else if (!isIdNumber(value)) {
                callback(new Error("身份证号有误"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: "blur",
          },
        ],
        phoneNumber: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("电话号码必须填写"));
              } else if (!isPhone(value)) {
                callback(new Error("电话号码有误"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: "blur",
          },
        ],
        sex: [{ required: true, message: "必须选择性别", trigger: "change" }],
        age: [{ required: true, message: "年龄必须填写", trigger: "change" }],
        nation: [{ required: true, message: "必须选择民族", trigger: "change" }],
        marriage: [{ required: true, message: "必须选择婚姻类型", trigger: "change" }],
        profession: [{ required: true, message: "必须选择职业类型", trigger: "change" }],
        height: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("身高必须填写"));
              } else if (!/^[0-9]+.?[0-9]*/.test(value)) {
                callback(new Error("身高必须为数字值"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: "blur",
          },
        ],
        weight: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("体重必须填写"));
              } else if (!/^[0-9]+.?[0-9]*/.test(value)) {
                callback(new Error("体重必须为数字值"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: "blur",
          },
        ],
        patientBmi: [
          {
            validator: (rule, value, callback) => {
              if (this.dataForm.patientBmi != null && this.dataForm.patientBmi != "") {
                callback();
              } else {
                callback(new Error("体质指数不能为空"));
              }
            },
            required: true,
            trigger: ["blur", "change"],
          },
        ],
        patientTerm: [
          {
            validator: (rule, value, callback) => {
              if (this.dataForm.patientTerm != null && this.dataForm.patientTerm != "") {
                callback();
              } else {
                callback(new Error("发病节气必须选择"));
              }
            },
            required: true,
            trigger: ["blur", "change"],
          },
        ],
        patientHistoryReliable: [
          { required: true, message: "病史是否可靠必须选择", trigger: "change" },
        ],
        birthAddress: [
          {
            validator: (rule, value, callback) => {
              if (!this.dataForm.birthAddress) {
                callback(new Error("出生地必须选择"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: ["blur", "change"],
          },
        ],
        presentAddress: [
          {
            validator: (rule, value, callback) => {
              if (!this.dataForm.presentAddress) {
                callback(new Error("现居住地必须选择"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: ["blur", "change"],
          },
        ],
        emergencyContactNumber: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("电话号码必须填写"));
              } else if (!isPhone(value)) {
                callback(new Error("电话号码有误"));
              } else {
                callback();
              }
            },
            required: true,
            trigger: "blur",
          },
        ],
        clinicTime: [
          {
            required: true,
            message: "就诊日期必须选择",
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  //方法集合
  methods: {
    /** 生成节气列表 */
    getSolarTerms() {
      const termTimeList = this.termTimeList;
      const data = {
        termTimeList: termTimeList,
      };
      if (!termTimeList || termTimeList.length !== 2) {
        this.$message({
          message: "请重新选择时间段",
          type: "warning",
        });
        return;
      }
      getSolarTerms(termTimeList).then((response) => {
        console.log(response.data);
        const list = response.data;
        this.$modal.msgSuccess("获取成功");
        this.patientTerm = list;
        if (list && list.length > 0) {
          this.getPatientTerm(list);
        }
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      subTree().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 病情分类选择框改变 */
    handleSubChange(value) {
      this.dataForm.subId = value[value.length - 1];
    },
    /** 保存并下一步 */
    saveOrUpdateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.dataForm.id) {
            // 修改用户信息
            updateBasicInfo(this.dataForm)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.$emit("parent-event");
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            // 添加用户信息
            saveBasicInfo(this.dataForm)
              .then((response) => {
                this.$modal.msgSuccess("添加成功");
                this.$parent.basicInfoId = response.data;
                this.dataForm.id = response.data;
                // 将数据保存到父级页面
                this.$emit("parent-event");
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 修改不执行下一步 */
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          // 修改用户信息
          this.buttonLoading = true;
          updateBasicInfo(this.dataForm)
            .then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.goBack();
            })
            .finally(() => {
              this.buttonLoading = false;
            });
        }
      });
    },
    /** 返回列表页面并销毁当前页 */
    goBack() {
      // 关闭当前标签页
      this.$store.dispatch("tagsView/delView", this.$route).then(() => {
        this.$router.push({
          path: "/gonitis/patient/info",
        });
      });
    },
    /** 发病节气变化 */
    getPatientTerm(value) {
      let str = "";
      for (let i = 0; i < value.length; i++) {
        str += value[i] + "/";
      }
      this.dataForm.patientTerm = str.substring(0, str.length - 1);
    },
    /** 获取体质指数 */
    getBMI() {
      const height = this.dataForm.height / 100;
      const weight = this.dataForm.weight;
      const patt = /^[0-9]+.?[0-9]*/;
      // 如果当前身高和当前体重都不为空
      if (patt.test(height) && patt.test(weight)) {
        this.dataForm.patientBmi = (weight / (height * height)).toFixed(2);
      }
    },
    /** 获取用户基本入组信息和基本信息 */
    fetchBasicInfo() {
      const basicId = this.dataForm.id;
      this.loading = true;
      queryBasicInfo(basicId).then((response) => {
        this.dataForm = response.data.basicInfo;
        this.patientInfo = response.data.patientInfo;
        this.subIds = response.data.subIds;
        this.patientTerm = this.dataForm.patientTerm.split("/");
        this.$nextTick(() => {
          this.$refs.birthAddress.setAddress(this.dataForm.birthAddress);
          this.$refs.presentAddress.setAddress(this.dataForm.presentAddress);
        });
        this.loading = false;
      });
    },
    /** 更新时初始化操作 */
    updateInit() {
      this.nationList = arrayJSON.nationList;
      this.patientTermList = arrayJSON.patientTermList;
      this.getDeptTree();
      this.fetchBasicInfo();
    },
    /** 新增初始化数据 */
    defaultInit() {
      this.getDeptTree();
      this.fetchPatientInfo();
      this.patientTermList = arrayJSON.patientTermList;
    },
    /** 获取患者信息 */
    fetchPatientInfo() {
      if (this.$parent.patientId) {
        const patientId = this.$parent.patientId;
        getPatientInfo(patientId).then((response) => {
          this.patientInfo = response.data;
          this.dataForm.patientId = this.patientInfo.id;
        });
      }
    },
    /** 给presentAddress赋值 */
    getPresentAddress(address) {
      this.dataForm.presentAddress = address;
    },
    /** 给birthAddress赋值 */
    getBirthAddress(address) {
      this.dataForm.birthAddress = address;
    },
  },
  /** 挂载函数 */
  mounted() {
    this.dataForm.id = this.$parent.basicInfoId;
    if (this.$parent.basicInfoId) {
      // 初始化数据
      this.isUpdate = true;
      this.updateInit();
    } else {
      this.isUpdate = false;
      this.defaultInit();
    }
  },
};
</script>
